package com.morsth.servlet;

import com.alibaba.fastjson.JSONObject;
import com.morsth.pojo.HolidayInfo;
import com.morsth.util.ToolsUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


@WebServlet("/api")
public class getHolidayInfo  extends HttpServlet {
    Logger  logger =  Logger.getLogger(getHolidayInfo.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String dateStr = req.getParameter("date");
        String fromIP = req.getRemoteAddr();
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
        SqlSession sqlSession = factory.openSession();
        HolidayInfo holidayInfo  =  sqlSession.selectOne("com.morsth.dao.getHolidayInfo",dateStr);
        sqlSession.close();
        HolidayInfo holidayInfo1  =  new HolidayInfo() ;
        if(holidayInfo == null){
            //如果数据库中没有获取到对象
             holidayInfo1.setDate(dateStr);
             Boolean ifWeekEnd  = ToolsUtils.checkIfWeekEnd(dateStr);
             holidayInfo1.setIfholiday(ifWeekEnd);
             if(ToolsUtils.checkYear(dateStr)){
                 holidayInfo1.setHolidaytype(ifWeekEnd?"周末":"上班");
             }else{
                 holidayInfo1.setHolidaytype(ifWeekEnd?"周末(数据库年份不存在,是否假日有可能不准确)":"上班(数据库年份不存在,是否假日有可能不准确)");
             }

        }else{
            holidayInfo1 = holidayInfo;
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        JSONObject  jsonObject = new JSONObject();
        jsonObject.put("date",holidayInfo1.getDate());
        jsonObject.put("ifHoliday",holidayInfo1.getIfholiday());
        jsonObject.put("holidayType",holidayInfo1.getHolidaytype());
        JSONObject  jsonObject1  =  new JSONObject();
        jsonObject1.put("status","ok");
        jsonObject1.put("result",jsonObject);
        logger.info("访问者IP:" + fromIP+"," + jsonObject.toJSONString());
        resp.getWriter().write(jsonObject1.toJSONString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
